import { defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite/plugins'
import Icons from "unplugin-icons/vite";

// 加兼容后缀
const postcssPresetEnv = require("postcss-preset-env")
// px转rem
const postCssPxToRem = require("postcss-pxtorem");

/* import ElementPlus from 'unplugin-element-plus/vite' */
// const fs = require('fs')
const path = require('path')// 预渲染
// const PrerenderSPAPlugin = require('prerender-spa-plugin-next')

// https://vitejs.dev/config/
export default ({ mode, command }) => {
    const env = loadEnv(mode, process.cwd())
    return defineConfig({
        // base: './',
        base: env.VITE_PUBLIC_PATH,
        // 开发服务器选项 https://cn.vitejs.dev/config/#server-options
        server: {
            open: true,
            port: 9000,
            proxy: {
                '/proxy': {
                    target: env.VITE_APP_API_BASEURL,
                    changeOrigin: command === 'serve' && env.VITE_OPEN_PROXY == 'true',
                    rewrite: path => path.replace(/\/proxy/, '')
                }
            }
        },
        // 构建选项 https://cn.vitejs.dev/config/#server-fsserve-root
        build: {
            chunkSizeWarningLimit: 500,
            outDir: mode == 'production' ? 'dist' : `dist-${mode}`,
            sourcemap: env.VITE_BUILD_SOURCEMAP == 'true',
            minify: 'terser',
            terserOptions: {
                compress: {
                    drop_debugger: true, /* 打包时删除 debugger */
                    drop_console: env.VITE_BUILD_DROP_CONSOLE == 'true'
                },
                output: {
                    /* 去掉注释内容 */
                    comments: true
                }
            }
        },
        optimizeDeps: {
            include: [
                'element-plus/es',
                'element-plus/es/components/message/style/css',
                'element-plus/es/components/notification/style/css',
                'element-plus/es/components/message-box/style/css'
            ]
        },
        plugins: [
            ...createVitePlugins(env, command === 'build'),
            Icons({
              // 自动安装图标库
              autoInstall: true,
            }),
            /* ElementPlus() */
            // BUG https://github.com/antfu/unplugin-vue-components/issues/361
            {
                name: 'dev-auto-import-element-plus',
                transform(code, id) {
                    if (command === 'serve' && /src\/main.js$/.test(id)) {
                        return {
                            code: code.replace('/* importElementPlusPlaceholder */', `
                                import ElementPlus from 'element-plus';
                                app.use(ElementPlus);
                            `),
                            map: null
                        }
                    }
                }
            }
        ],
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'src'),
                'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
            }
        },
        rollupOptions: {
            output: {
                chunkFileNames: 'static/js/[name]-[hash].js',
                entryFileNames: 'static/js/[name]-[hash].js',
                assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
            }
        },
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@use "@/assets/styles/globals.scss" as *;`
                    // additionalData: `@use "@/assets/styles/globals.scss" as *;@use "@/assets/styles/element/index.scss" as *;`
                }
            },
            postcss: {
                plugins: [
                    postcssPresetEnv(),
                    // 配置rem
                    postCssPxToRem({
                        // 换算基数，
                        rootValue: 16,
                        //允许REM单位增长到的十进制数字,小数点后保留的位数
                        unitPrecision: 5,
                        propList: ['*'],
                        //默认false，可以（reg）利用正则表达式排除某些文件夹的方法，例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem，请把此属性设为默认值
                        // exclude: /(node_module)/,
                        //（布尔值）允许在媒体查询中转换px。
                        mediaQuery: true,
                        //要忽略并保留为px的选择器，本项目我是用的elementpLus ui框架，所以加了.el，你可以自己配
                        // selectorBlackList: ['.el'],
                        //设置要替换的最小像素值
                        minPixelValue: 1,
                    })
                ]
            }
        },
        define: {
            // enable hydration mismatch details in production build
            __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'true'
        }
    })
}
